var md5 = require('blueimp-md5');
var Base64 = require('js-base64').Base64;
var moment = require('moment');
var request = require('request');

function randomCode(length) {
    var chars = ['0','1','2','3','4','5','6','7','8','9'];
    var result = "";

    for ( var i=0; i<length; i++ ) {
        var index = Math.ceil(Math.random()*9);
        result += chars[index];
    }

    return result;
}
exports.randomCode = randomCode;

function sendCode(phone, code, callback) {
    var ACCOUNT_SID = '8aaf070855b647ab0155b9f80994058a';
    var AUTH_TOKEN = 'aa8aa679414e49df8908ea5b3d043c24';
    var Rest_URL = 'https://app.cloopen.com:8883';
    var AppID = '8aaf070855b647ab0155b9f809f90590';

    var time = moment().format('YYYYMMDDHHmmss');
    var sigParameter = md5(ACCOUNT_SID+AUTH_TOKEN+time);
    var url = Rest_URL+'/2013-12-26/Accounts/'+ACCOUNT_SID+'/SMS/TemplateSMS?sig='+sigParameter;

    var body = {
        to : phone,
        appId : AppID,
        templateId : '1',
        "datas": [code, "1"]
    }
    var headers = {
        'Accept' :'application/json',
        'Content-Type' :'application/json;charset=utf-8',
        'Content-Length': JSON.stringify(body).length+'',
        'Authorization' : Base64.encode(ACCOUNT_SID + ':' + time)
    }

    request({
        method : 'POST',
        url : url,
        headers : headers,
        body : body,
        json : true
    }, function (error, response, body) {
        console.log(error, response, body);

        callback(body.statusCode==='000000');
    });
}
exports.sendCode = sendCode;
